<?php

declare(strict_types=1);

namespace App\Controllers;

use Core\Controller;
use Core\Flash;

class Register extends Controller
{
    /**
     * 显示用户注册表单
     */
    public function index()
    {
        // 如果用户已登录，重定向到首页
        if ($this->getCurrentUser()) {
            redirect('/');
        }

        $data = [
            'title'      => '用户注册',
            'csrf_token' => $this->app->generateCsrfToken(),
            'errors'     => $_SESSION['register_errors'] ?? [],
            'old'        => $_SESSION['register_old'] ?? []
        ];

        Flash::success('用户创建成功！');

        $this->render('user/register', $data);
    }

    /**
     * 提交注册
     */
    public function register(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            $this->app->json(['error' => '仅支持 POST 请求'], 405);
            return;
        }

        // 验证 CSRF 令牌
        if (!$this->app->validateCsrfToken()) {
            $this->app->json(['error' => '无效的 CSRF 令牌'], 403);
            return;
        }

        // 验证输入数据
        $validation = $this->app->validate([
            'username' => 'required|min:3|max:20',
            'password' => 'required|min:6|max:32',
            'email'    => 'required|email',
            'confirm_password' => 'required'
        ]);

        if (!$validation['valid']) {
            $this->app->json([
                'success' => false,
                'errors' => $validation['errors']
            ], 400);
            return;
        }

        $data = $validation['data'];
        
        // 验证两次密码是否一致
        if ($data['password'] !== $data['confirm_password']) {
            $this->app->json([
                'success' => false,
                'error' => '两次输入的密码不一致'
            ], 400);
            return;
        }

        // 检查用户名/邮箱是否已存在
        $stmt = $this->app->query(
            "SELECT id FROM users WHERE username = :username OR email = :email",
            [
                'username' => $data['username'],
                'email' => $data['email']
            ]
        );

        if ($stmt->fetch()) {
            $this->app->json([
                'success' => false,
                'error' => '用户名或邮箱已被注册'
            ], 409);
            return;
        }

        try {
            // 密码哈希加密
            $hashedPassword = password_hash($data['password'], PASSWORD_DEFAULT);
            
            // 插入新用户
            $userId = $this->app->insert('users', [
                'username' => $data['username'],
                'password' => $hashedPassword,
                'email' => $data['email']
            ]);

            if (!$userId) {
                throw new \RuntimeException('用户创建失败');
            }

            $this->app->json([
                'success' => true,
                'message' => '注册成功！请登录',
                'user_id' => $userId
            ]);
        } catch (\Throwable $e) {
            $this->app->json([
                'success' => false,
                'error' => '注册失败: ' . $e->getMessage()
            ], 500);
        }
    }
}
